package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.SkuHasStockTo;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.BeanCopyUtils;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.to.SkuWareHasStockTo;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();

        // 封装仓库id
        String wareId = (String) params.get("wareId");
        if (StringUtils.isNotBlank(wareId) && !"0".equalsIgnoreCase(wareId)) {
            wrapper.eq("ware_id", wareId);
        }

        // 封装商品id
        String skuId = (String) params.get("skuId");
        if (StringUtils.isNotBlank(skuId) && !"0".equalsIgnoreCase(skuId)) {
            wrapper.eq("sku_id", skuId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 采购入库
     *
     * @param skuId  采购商品id
     * @param wareId 仓库id
     * @param skuNum 采购数量
     */
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        // 查询该仓库是否有该商品库存记录
        List<WareSkuEntity> wareSkuEntityList = baseMapper.selectList(
                new QueryWrapper<WareSkuEntity>()
                        .eq("sku_id", skuId)
                        .eq("ware_id", wareId));
        if (CollectionUtils.isEmpty(wareSkuEntityList)) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            try {
                R r = productFeignService.skuInfo(skuId);
                if (r.getCode() == 0) {
                    Map<String, Object> skuInfo = (Map<String, Object>) r.get("skuInfo");
                    wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));
                }
            } catch (Exception ignored) {
            }
            wareSkuEntity.setStock(skuNum);
            baseMapper.insert(wareSkuEntity);
        } else {
            // 在原有库存记录上增加库存
            baseMapper.addStock(skuId, wareId, skuNum);
        }
    }

    /**
     * 查询商品库存数
     *
     * @param skuId skuId
     * @return 库存数
     */
    @Override
    public Long queryWareSkuBySkuId(Long skuId) {
        List<WareSkuEntity> wareSkuEntityList = baseMapper.selectList(
                new QueryWrapper<WareSkuEntity>()
                        .eq("sku_id", skuId));
        return wareSkuEntityList.stream().map(item -> item.getStock() - item.getStockLocked()).count();
    }

    /**
     * 查询sku是否有库存
     *
     * @param skuIds sku Id列表
     * @return 是否有库存
     */
    @Override
    public List<SkuHasStockTo> getSkuHasStock(List<Long> skuIds) {
        List<SkuHasStockTo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockTo skuHasStockVo = new SkuHasStockTo();
            skuHasStockVo.setSkuId(skuId);
            Long count = baseMapper.getSkuStock(skuId);
            if (count == null) {
                log.error("该skuId：{}没有库存记录", skuId);
                skuHasStockVo.setHasStock(false);
            } else {
                skuHasStockVo.setHasStock(count > 0);
            }
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 为订单锁定库存
     *
     * @param wareSku 锁定库存传输vo
     */
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public void orderLockStock(WareSkuLockVo wareSku) {
        /*
         * 保存库存工作单：便于追溯
         */
        WareOrderTaskEntity orderTaskEntity = new WareOrderTaskEntity();
        orderTaskEntity.setOrderSn(wareSku.getOrderSn());
        wareOrderTaskService.save(orderTaskEntity);

        List<OrderItemVo> locks = wareSku.getLocks();

        // 查询有库存的仓库id
        List<SkuWareHasStockTo> collect = locks.stream().map(item -> {
            SkuWareHasStockTo stockTo = new SkuWareHasStockTo();
            stockTo.setSkuId(item.getSkuId());
            List<Long> wareIds = baseMapper.listWareIdHashSkuStock(item.getSkuId());
            stockTo.setWareId(wareIds);
            stockTo.setNum(item.getCount());
            return stockTo;
        }).collect(Collectors.toList());

        // 锁定库存
        for (SkuWareHasStockTo hasStock : collect) {
            boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            Integer num = hasStock.getNum();
            List<Long> wareIds = hasStock.getWareId();
            if (CollectionUtils.isEmpty(wareIds)) {
                throw new NoStockException(skuId);
            }
            for (Long wareId : wareIds) {
                Long count = baseMapper.lockSkuStock(skuId, wareId, num);
                if (count == 1) {
                    // 当前仓库锁成功
                    skuStocked = true;
                    /*
                     *保存库存工作单的详情：便于追溯
                     */
                    WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity(null, skuId, null, hasStock.getNum(), orderTaskEntity.getId(), wareId, 1);
                    wareOrderTaskDetailService.save(taskDetailEntity);
                    // 发送库存锁定成功的消息
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setId(orderTaskEntity.getId());
                    // 锁失败后，工作单会靠事务进行回滚，而库存需要根据mq进行回滚：防止回滚后数据找不到
                    stockLockedTo.setDetailTo(BeanCopyUtils.copy(taskDetailEntity, StockDetailTo.class));
                    rabbitTemplate.convertAndSend("stock-event-exchange",
                            "stock.locked",
                            stockLockedTo);
                    break;
                }
            }
            if (!skuStocked) {
                // 当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }
    }

    /**
     * 根据库存工作单详情数据解锁库存
     *
     * @param skuId  商品id
     * @param wareId 仓库id
     * @param skuNum 解锁数量
     */
    @Override
    public void unLockStock(Long skuId, Long wareId, Integer skuNum, Long detailToId) {
        // 订单工作单更新状态
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(detailToId);
        entity.setLockStatus(2);
        // 解锁库存
        baseMapper.unLockStock(skuId, wareId, skuNum);
    }

    /**
     * 主动解锁库存
     *
     * @param orderTo 订单实体
     */
    @Transactional
    @Override
    public void unLockStock(OrderTo orderTo) {
        // 获取订单最新状态
        R r = orderFeignService.queryStatusByOrderSn(orderTo.getOrderSn());
        if (r.getCode() == 0) {
            OrderVo orderVo = r.getData(new TypeReference<OrderVo>() {
            });
            if (orderVo.getStatus() == 0) {
                String orderSn = orderTo.getOrderSn();
                // 获取最新库存状态，防止重复解锁库存
                WareOrderTaskEntity task = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
                Long taskId = task.getId();
                // 查询工作单详情中没有解锁的库存，进行解锁
                List<WareOrderTaskDetailEntity> detailEntityList = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                        .eq("task_id", taskId)
                        .eq("lock_status", 1)
                );
                for (WareOrderTaskDetailEntity detailEntity : detailEntityList) {
                    unLockStock(detailEntity.getSkuId(), detailEntity.getWareId(), detailEntity.getSkuNum(), detailEntity.getId());
                }
                // 关闭订单
                orderFeignService.closeByOrderSn(orderTo.getOrderSn());
            }
        }
    }

}